package com.etone.smartAudit.config;

import cn.hutool.crypto.digest.DigestUtil;
import com.etone.smartAudit.annotation.FormAop;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.service.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

//@Component
//@Aspect
public class FormAopIntercept {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserComment userComment;

    //这里需要注意了，这个是将自己自定义注解作为切点的根据，路径一定要写正确了
    @Pointcut(value = "@annotation(com.etone.smartAudit.annotation.FormAop)")
    public void access() {
        System.out.println("-接口请求拦截开始-" + new Date());
    }

    //进来切点世界，先经过的第一个站
    @Before("access()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        System.out.println("-接口请求拦截开始-" + new Date());

    }

    //环绕增强，是在before前就会触发
    @Around("@annotation(formAop)")
    public Object around(ProceedingJoinPoint pjp, FormAop formAop) throws Throwable {
        System.out.println("-aop 日志环绕阶段-" + new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();


        //获取当前登录用户
        Admin admin = userComment.getCurAdmin();
        String url = request.getRequestURL().toString();
        if (admin != null) {
            String key = DigestUtil.md5Hex(url + admin.getId());
            String cache = redisUtil.get(key);
            if (cache != null) {
                throw new CustomParameterizedException("正在执行中，请稍后!");
            } else {
                redisUtil.setEx(key, "66", 14, TimeUnit.SECONDS);
            }
        }
        return pjp.proceed();
    }

    //进来切点这，最后经过的一个站，也是方法正常运行结束后
    @After("access()")
    public void after(JoinPoint joinPoint) {
        System.out.println("-接口请求拦截结束-" + new Date());
    }


}
